<template>

  <!--  卡片区域  -->
  <n-card>
    <!--    工具栏    -->
    <n-space justify="end" style="padding-bottom: 15px;">
      <!--  新建按钮    -->
      <n-button @click="showModal = true" type="info" style="width: 80px; height: 30px">
        <n-icon size="18">
          <add/>
        </n-icon>
        新建
      </n-button>
      <!--刷新-->
      <n-tooltip trigger="hover">
        <template #trigger>
          <n-button text style="font-size: 20px; width:22px; height:32px;" @click="refresh">
            <n-icon>
              <refresh-sharp />
            </n-icon>
          </n-button>
        </template>
        <span>刷新</span>
      </n-tooltip>
      <!--密度-->
      <n-popselect v-model:value="densityValue" :options="densityOptions" trigger="click">
        <n-tooltip trigger="hover">
          <template #trigger>
            <n-button text style="font-size: 20px; width:22px; height:32px; margin-left: 11px">
              <n-icon>
                <auto-fit-height20-regular />
              </n-icon>
            </n-button>
          </template>
          <span>密度</span>
        </n-tooltip>
      </n-popselect>
      <!--列设置-->
      <n-tooltip trigger="hover">
        <template #trigger>
          <n-popover trigger="click" placement="bottom-end">
            <template #trigger>
              <n-button text style="font-size: 20px; width:22px; height:32px; margin-bottom: 2px; margin-left: 11px">
                <n-icon>
                  <Settings20Regular />
                </n-icon>
              </n-button>
            </template>
            <template #header>
              <n-checkbox label="列展示" v-model:checked="allChecked" @update:checked="allChange" />
            </template>
            <n-space vertical>
              <n-checkbox v-for="item in checkboxList" :key="item.name" :label="item.name" v-model:checked="item.checked" @update:checked="itemChange" />
            </n-space>
          </n-popover>
        </template>
        <span>列设置</span>
      </n-tooltip>
    </n-space>
    <!--    数据表格    -->
    <n-data-table
        :columns="columns"
        :data="data"
        :pagination="pagination"
        :bordered="false"
        :size="densityValue"
        :loading="loading"
        scroll-x="1200"
    />
  </n-card>
  <!--  新建模态框  -->
  <n-modal v-model:show="showModal" preset="card" :style="bodyStyle" title="添加" :segmented="segmented">
    <!--表单-->
    <n-form-item path="user.name" label="问题详解">
      <n-input
          clearable
          v-model:value="formValue.user.name"
          type="textarea"
          placeholder="请输入问题详解"
      >
      </n-input>
    </n-form-item>
    <n-form-item  label="答案详解">
      <n-input
          clearable
          type="textarea"
          v-model:value="answerValue"
          placeholder="请输入答案详解"

      >
      </n-input>
    </n-form-item>


    <n-form-item label="是否启用">
      <n-select
          v-model:value="enableValue"
          :options="enable_status"
          placeholder="是否启用"
          clearable
      />
    </n-form-item>
    <n-form-item label="推荐值">
      <n-input-number
          v-model:value="weightValue"
          placeholder="请输入推荐值"
          clearable
      />
    </n-form-item>
    <template #footer>
      <n-space justify="end">
        <n-button @click="cancel">取消</n-button>
        <n-button type="info" @click="sure">确定</n-button>
      </n-space>
    </template>
  </n-modal>


  <!--  编辑模态框-->
  <n-modal v-model:show="showEditModal" preset="card" :style="bodyStyle" title="编辑" :segmented="segmented">
    <n-form :rules="rulesEdit" :model="formEditValue">
      <n-form-item path="user.name" label="问题详解">
        <n-input
            clearable
            v-model:value="formEditValue.user.name"
            type="textarea"

            placeholder="请输入问题详解"
        >
        </n-input>
      </n-form-item>
      <n-form-item  label="答案详解">
        <n-input
            clearable
            v-model:value="answerEditValue"
            type="textarea"
            placeholder="请输入答案详解"

        >
        </n-input>
      </n-form-item>


      <n-form-item label="是否启用">
        <n-select
            v-model:value="enableEditValue"
            :options="enable_status"
            placeholder="是否启用"
            clearable
        />
      </n-form-item>
      <n-form-item label="推荐值">
        <n-input-number
            v-model:value="weightEditValue"
            placeholder="请输入推荐值"
            clearable
        />
      </n-form-item>
    </n-form>
    <template #footer>
      <n-space justify="end">
        <n-button @click="cancelEdit">取消</n-button>
        <n-button type="info" @click="sureEdit">确定</n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script>
import {defineComponent, h, reactive, ref ,onMounted} from 'vue'
import {NButton, NForm, NFormItem, NInput, NTag, NFlex, NIcon, NImage, NGradientText,NText} from "naive-ui";
import { Add } from "@vicons/ionicons5"
import { RefreshSharp } from "@vicons/material"
import { AutoFitHeight20Regular ,Settings20Regular} from "@vicons/fluent"
import { LeftOutlined , RightOutlined} from "@vicons/antd"
import {ListService,SaveService,Renew,Delete} from '@/api/service'

export default defineComponent({
  components: {
    Add,
    RefreshSharp,
    AutoFitHeight20Regular,
    Settings20Regular,
    LeftOutlined,
    RightOutlined
  },
  setup(){
    const message = window.$message
    /*  数据表格  */
    // 创建表格列模版
    const createColumns = () => {
      return [
        {
          title: "序号",
          key: "index",
          width:50,
          render(row, index) {
            return index + 1;
          }
        },
        {
          title: "问题",
          key: "name",
          width:100,
          ellipsis: {
            tooltip: {
              width: 300,
            },
          }
        },
        {
          title: "答案",
          key: "answer",
          width:160,
          ellipsis: {
            tooltip: {
              width: 300,
            },
          }
        },
        {
          title: "是否启用",
          key: "status",
          width:100,
          render(row) {
            switch (row.status) {
              case 1:
                return h(
                    NText,
                    {
                      strong: true,
                      size:'medium',
                      bordered:false,
                      style:'color:black'
                    },
                    { default: () => "启用" }
                )
              case 0:
                return h(
                    NTag,
                    {
                      strong: true,
                      size: "small",
                      type:'success',
                    },
                    { default: () => "禁用" }
                )
            }
          }
        },
        {
          title: "推荐值",
          key: "weight",
          width:100,
        },
        {
          title: "操作",
          key: "actions",
          fixed:'right',
          width:100,
          render(row) {
            return h(
                NFlex,
                {
                  size: "small",
                },
                {
                  default: () => [
                    h(
                        NButton,
                        {
                          text: true,
                          color: "#3FA2FE",
                          onClick: () => {
                            console.log(row)
                            showEditModal.value = true
                            formEditValue.value.user.name = row.name
                            answerEditValue.value = row.answer
                            weightEditValue.value = row.weight
                            enableEditValue.value = row.status
                            editId.value = row.editId
                          }
                        },
                        { default: () => "编辑" }
                    ),
                    h(
                        NButton,
                        {
                          text: true,
                          color: "#3FA2FE",
                          onClick: () => {
                            ListService().then(i => {
                              const content = i.data.list
                              content.forEach((item) => {
                                if (item.question === row.name){
                                  row.id = item.id
                                  Delete(row.id).then(res => {
                                    console.log(row.id)
                                    console.log(res)
                                    if (res.code === 0) {
                                      message.success(res.message)
                                      // 更新数据
                                      window.location.reload()
                                    } else {
                                      message.error(res.message)
                                    }
                                  })
                                }
                              })
                            })
                          }
                        },
                        { default: () => "删除" }
                    )
                  ]
                }
            )
          }
        }
      ];
    };
    // 调用列模版
    const columns = createColumns()
    // 表格数据
    let data = reactive([])

    // 获取用户列表数据
    let getData = ()=>{
      ListService().then(res => {
        const content = res.data.list
        console.log(content)
        // 遍历数据库数据
        content.forEach((item, index) => {
          data.push({
            key:index,
            name:item.question,
            answer:item.answer,
            status:item.enable_status,
            weight:item.weight,
            editId:item.id
          })
        })
        total.value = data.length
      })
    }
    // 调用数据
    getData()
    // 总条数
    const total = ref(data.length);
    // 总页数
    const page = ref(Math.ceil(data.length / 10));
    // 当前所在页数
    const currentPage = ref(1);
    // 分页
    const pagination = {
      prev:()=>{
        return h(
            NIcon,
            {
              onClick:()=>{
                currentPage.value --
              }
            },
            {
              default: () => h(LeftOutlined)
            }
        )
      },
      next:()=>{
        return h(
            NIcon,
            {
              onClick:()=>{
                currentPage.value ++
              }
            },
            {
              default: () => h(RightOutlined)
            }
        )
      },
      prefix:()=>{
        const range = [currentPage.value * 10 - 9, currentPage.value * 10];
        if (currentPage.value <= 1) {
          return `第 1 条到第 ${range[1]} 条 / 总共 ${total.value} 条`;
        }else if (currentPage.value >= page.value) {
          return `第 ${range[0]} 条到第 ${total.value} 条 / 总共 ${total.value} 条`;
        }else if (currentPage.value > 1 && currentPage.value < page.value) {
          return `第 ${range[0]} 条到第 ${range[1]} 条 / 总共 ${total.value} 条`;
        }
      },
    }


    /*  工具栏  */
    // 模态框
    /*新建、编辑*/
    // 显示新建-模态框
    const showModal = ref(false)
    // 显示编辑-模态框
    const showEditModal = ref(false)
    // 模态框样式
    const bodyStyle = {
      width: "640px",
    }
    const segmented = {
      content: "soft",
      footer: "soft"
    }
    // 取消新建-模态框
    function cancel() {
      showModal.value = false
    }
    // 取消编辑-模态框
    function cancelEdit() {
      showEditModal.value = false
    }
    // 新建-确定提交
    function sure() {
      let formData = {
        question:formValue.value.user.name,
        answer:answerValue.value,
        enable_status:enableValue.value,
        weight:weightValue.value
      }
      // 添加到数据库
      SaveService(formData).then(res => {
        console.log(res)
        if (res.code === 0) {
          message.success(res.message)
          // 刷新数据
          window.location.reload()
          cancel()
          window.location.reload()
        } else {
          message.error(res.message)
        }
      })

    }
    // 编辑-id
    let editId = ref()
    let editAvatar = ref()
    // 编辑-确定提交
    function sureEdit() {
      let formData = {
        question:formEditValue.value.user.name,
        answer:answerEditValue.value,
        enable_status:enableEditValue.value,
        weight:weightEditValue.value,
        id:editId.value
      }
      console.log(formData)
      // 添加到数据库
      Renew(formData).then(res => {
        console.log(res)
        if (res.code === 0) {
          message.success(res.message)
          window.location.reload()
        }else {
          message.error(res.message)
        }
      })
      showEditModal.value = true
    }
    // 新建-表单信息
    const formValue = ref({
      user: {
        name: "",
        mobile: "",
        password: '',
      }
    })
    // 编辑-表单信息
    const formEditValue = ref({
      user: {
        name: '',
        mobile: '',
      }
    })



    // 新建-角色身份
    const roleValue = ref()
    // 编辑-角色身份
    const roleEditValue = ref()
    // 账号角色身份列表
    const role_id = ref([
      {label: "招聘者", value: 1},
      {label: "分行管理员", value: 2},
      {label: "总行管理员", value: 3},
    ])
    // 答案
    const answerValue = ref()
    // 编辑答案
    const answerEditValue = ref()
    // 权重
    const weightValue = ref()
    // 编辑权重
    const weightEditValue = ref()
    // 新建-账号状态
    const enableValue = ref(1)
    // 编辑-账号状态
    const enableEditValue = ref()
    // 账号状态列表
    const enable_status = ref([
      {label: "启用", value: 1},
      {label: "禁用", value: 0},
    ])
    // 新建验证规则
    const rules = {
      user: {
        name: {
          required: true,
          trigger: "blur",
          message: "请输入用户名！"
        },
        mobile: {
          required: true,
          trigger: "blur",
          message: "请输入手机号！"
        },
        password: {
          required: true,
          trigger: "blur",
          message: "请输入密码！"
        },
      }
    };
    // 编辑验证规则
    const rulesEdit = {
      user: {
        name: {
          required: true,
          trigger: "blur",
          message: "请输入用户名！"
        },
        mobile: {
          required: true,
          trigger: "blur",
          message: "请输入手机号！"
        },
      }
    };


    /*刷新*/
    // 加载
    const loading = ref(false)
    // 刷新
    function refresh() {
      // loading.value = true
      // setTimeout(() => {
      //   // getData()
      //   loading.value = false
      // }, 1000)
      window.location.reload()
    }
    /*密度*/
    // 密度事件数据
    const densityOptions = [
      {
        label: "默认",
        value: "large"
      },
      {
        label: "中等",
        value: "medium"
      },
      {
        label: "紧密",
        value: "small",
      },
    ]
    // 默认密度
    const densityValue = ref('medium')

    /*列设置*/
    // 复选框全选
    const allChecked = ref(true)
    // 复选框列表
    const checkboxList = ref([])
    // 列表添加数据
    for (let i = 0;i < columns.length; i++){
      checkboxList.value.push({name: columns[i].title, checked: true})
    }
    // 全选改变事件
    const allChange = ()=>{
      if (allChecked.value) {
        checkboxList.value.forEach(item => {item.checked = true})
      } else {
        checkboxList.value.forEach(item => {item.checked = false})
      }
    }
    // 复选框单个改变事件
    const itemChange = ()=>{
      if (checkboxList.value.every(item => item.checked)) {
        allChecked.value = true
      } else {
        allChecked.value = false
      }
    }



    return {
      // 模态框
      weightValue,
      weightEditValue,
      answerValue,
      answerEditValue,
      showModal,
      showEditModal,
      bodyStyle,
      segmented,
      cancel,
      cancelEdit,
      sure,
      sureEdit,
      formValue,
      formEditValue,
      rules,
      rulesEdit,
      roleValue,
      roleEditValue,
      role_id,
      enableValue,
      enableEditValue,
      enable_status,
      // 数据表格
      densityOptions,
      densityValue,
      data,
      columns,
      pagination,
      loading,
      refresh,
      page,
      checkboxList,
      allChecked,
      allChange,
      itemChange,
      editId,
      editAvatar

    }
  }

})
</script>

<style scoped>

</style>